package com.android.vestel.photoroid;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class PicasaFormActivity extends Activity {

	private DataHelper dataHelper;
	private PicasaClient picasaClient;
	private EditText unameEditText;
	private EditText passEditText;
	private String selectedAlbumID;
	private String ProgramState;

	private String username;
	private String password;
	String TAG = "PicasaFormActivity";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.picasa);
		Log.e("picasaFormActivity", "created");

		unameEditText = (EditText) findViewById(R.id.P_EmailEditText);
		passEditText = (EditText) findViewById(R.id.P_passwordEditText);
		Button loginButton = (Button) findViewById(R.id.P_signIn);

		loginButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(final View v) {
				Log.e("picasaFormActivity", "login clicked");
				if (ProgramState
						.equals(PhotoroidService.PROG_STAT_FLICKR_DISABLED)
						|| ProgramState
								.equals(PhotoroidService.PROG_STAT_FLICKR_ENABLED)) {
					openDBConnection();
					dataHelper.deleteAllPhotos();
					File photoroidDir = new File(SyncPhotos.downloadDir);

					if (photoroidDir.exists()) {
						File[] flist = photoroidDir.listFiles();
						for (File f : flist) {
							if (f.isFile()) {
								Log.e(TAG,
										"File deleted = " + f.getAbsolutePath());
								f.delete();
							}
						}
						photoroidDir.delete();

						closeDBConnection();
					}
				}
				username = unameEditText.getText().toString().trim();
				password = passEditText.getText().toString().trim();

				// TODO: uname and password validation
				// initializeClient();
				picasaClient = new PicasaClient(username, password);

				Thread th = new Thread(new Runnable() {
					@Override
					public void run() {
						// if false username and password is not true
						if (picasaClient.OpenAuthentication()) {
							Log.e("picasaFormActivity",
									"picasa connection authenticated");
							picasaClient.parseAlbumIDs();

							// kill the background service
							stopService(new Intent(v.getContext(),
									PhotoroidService.class));
							Log.e("picasaFormActivity", "service stopped");
							openDBConnection();
							dataHelper.updateAccountTable(username, password);
							closeDBConnection();
							// get albumlist from picasa
							ArrayList<String> albumNames = picasaClient
									.getAlbumNames();
							ArrayList<String> albumIDs = picasaClient
									.getAlbumIDs();

							Log.e("picasaFormActivity", "albums fetched");
							// go to album selection
							Bundle b = new Bundle();
							b.putStringArrayList("albumNames", albumNames);
							b.putStringArrayList("albumIDs", albumIDs);
							Intent goToAlbumSelection = new Intent(v
									.getContext(),
									PicasaAlbumSelectionActivity.class);
							goToAlbumSelection.putExtras(b);
							Log.e("picasaFormActivity", "go to album view");
							startActivityForResult(goToAlbumSelection, 0);

						} else {
							Log.e("PicasaFormActivity",
									"Picasa is not reachable or wrong username or password.");
							// TODO alertbox
						}
					}
				});

				th.start();
			}
		});

		// openDBConnection();
		updateProgramState();
		Log.e("PicasaFormActivity", "ProgramState is " + ProgramState);
		// if any user details exist before show them on
		openDBConnection();
		if (ProgramState.equals(PhotoroidService.PROG_STAT_PICASA_ENABLED)
				|| ProgramState
						.equals(PhotoroidService.PROG_STAT_PICASA_DISABLED)
				|| !(dataHelper.selectAllOfAccounts().get(DataHelper.USERNAME)
						.equals("null") & dataHelper.selectAllOfAccounts()
						.get(DataHelper.PASSWORD).equals("null"))) {
			Log.e("PicasaFormActivity", "There is picasa data in DB");
			username = dataHelper.selectAllOfAccounts()
					.get(DataHelper.USERNAME);
			password = dataHelper.selectAllOfAccounts()
					.get(DataHelper.PASSWORD);
			closeDBConnection();
			Log.e("PicasaFormActivity", "Username=" + username);

			if (username != "null" || password != "null") {
				Log.e("PicasaFormActivity", "Username or Password is not null");

				unameEditText.setText(username);
				passEditText.setText(password);
			} else
				Log.e("PicasaFormActivity",
						"Username or Password is null so not shown");

		} else {
			Log.e("PicasaFormActivity", "There is no picasa data in DB");
			username = "";
			password = "";
			unameEditText.setText(username);
			passEditText.setText(password);
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.e("PicasaFormActivity", "onActivityResult");
		if (requestCode == resultCode) {
			Log.e("PicasaFormActivity", "result = request");
			Bundle b = new Bundle();
			// get selected album name from album selection
			b.clear();
			if (data != null) {
				Log.e("PicasaFormActivity", "Data is not null");
				b = data.getExtras();
				if (b.containsKey("selectedAlbumID")) {
					Log.e("PicasaFormActivity", "Contains the sent key");
					if ((selectedAlbumID = b.getString("selectedAlbumID")) != "-1") {// if
																						// any
																						// chosen
						Log.e("PicasaFormActivity", "An album is selected");
						// update database
						updateProgramState(
								PhotoroidService.PROG_STAT_PICASA_ENABLED,
								"picasa");
						openDBConnection();
						dataHelper.updateAccountTable(username, password);
						// update album name on database
						dataHelper.updateVarTable(selectedAlbumID, "", "");
						closeDBConnection();
						Toast.makeText(this, "Picasa Account Enabled",
								Toast.LENGTH_LONG);
						// start background service with new options
						startService(new Intent(this, PhotoroidService.class));
						setResult(0);
						finish();
					} else {
						Log.e("PicasaFormActivity",
								"Intent received with no album selected or there is no available album.");
						// TODO alertbox
						setResult(0);
						finish();
					}
				} else {
					Log.e("PicasaFormActivity",
							"Intent received with no selected album ID data.");
				}
			} else
				Log.e("PicasaFormActivity", "data is null");
		} else
			Log.e("PicasaFormActivity", "Request Code = " + requestCode
					+ " Result Code = " + resultCode);
	}

	// @Override
	// protected void onStart() {
	// super.onStart();
	// // if any user details exist before show them on
	// if (ProgramState == PhotoroidService.PROG_STAT_PICASA_ENABLED
	// || ProgramState == PhotoroidService.PROG_STAT_PICASA_DISABLED) {
	// username = dataHelper.selectAllOfAccounts().get(DataHelper.USERNAME);
	// password = dataHelper.selectAllOfAccounts().get(DataHelper.PASSWORD);
	//
	// if (username != "null" || password != "null") {
	// unameEditText.setText(username);
	// passEditText.setText(password);
	// }
	//
	// } else {
	// username = "";
	// password = "";
	// unameEditText.setText(username);
	// passEditText.setText(password);
	// }
	// }
	// protected void onActivityResult(int requestCode, int resultCode,
	// Intent data) {
	// Log.e("PicasaFormActivity","onActivityResult");
	// if (requestCode == resultCode) {
	// Bundle b = new Bundle();
	// // get selected album name from album selection
	// b.clear();
	// b = data.getExtras();
	// if (b.containsKey("selectedAlbumID")) {
	// if ((selectedAlbumID = b.getString("selectedAlbumID")) != "-1") {// if
	// any chosen
	// // update database
	// updateProgramState(PhotoroidService.PROG_STAT_PICASA_ENABLED, "picasa");
	// dataHelper.updateAccountTable(username, password);
	// // update album name on database
	// dataHelper.updateVarTable(selectedAlbumID, "", "");
	// Toast.makeText(this, "Picasa Account Enabled", Toast.LENGTH_LONG);
	// // start background service with new options
	// startService(new Intent(this,
	// PhotoroidService.class));
	// setResult(0);
	// finish();
	// }
	// else {
	// Log.e("PicasaFormActivity","Intent received with no album selected or there is no available album.");
	// //TODO alertbox
	// setResult(0);
	// finish();
	// }
	// }
	// else {
	// Log.e("PicasaFormActivity","Intent received with no selected album ID data.");
	// }
	// }
	// }

	private void openDBConnection() {
		if (dataHelper == null) {
			dataHelper = new DataHelper(this);
		}
		Log.e("PicasaFormActivity", "Database Connection Opened");
	}

	private void closeDBConnection() {
		if (dataHelper != null) {
			dataHelper.closeDB();
			dataHelper = null;
		}
		Log.e("PicasaFormActivity", "Database Connection Closed");

	}

	private String updateProgramState() {
		openDBConnection();
		ProgramState = dataHelper.selectAllOfSetting().get(
				DataHelper.PROGRAM_STATE);
		closeDBConnection();
		return ProgramState;
	}

	private void updateProgramState(String newProgramState,
			String newServiceProvider) {
		ProgramState = newProgramState;
		openDBConnection();
		dataHelper.updateSettingTable(newProgramState, newServiceProvider);
		closeDBConnection();
	}
//	@Override
//	protected void onPause() {
//		setResult(0);
//		finish();
//		super.onPause();
//	}
}
